﻿using System;
using Midi;
using Microsoft.Pex.Framework;

namespace AutomaTones.HW_Sense_Compute {
    /// <summary>
    /// Handles the setup of the Virtual Midi driver needed to communicate from our program to the other application handling sound.
    /// </summary>
    /// <author>Anders Bech Mellson, anbh@itu.dk</author>
    [PexClass]
    partial class ConnectVirtualMidi : IConnect
    {
        public static OutputDevice Out;

        int? _outDevice;
        const String Error = "No Virtual Midi driver present. Have you installed the driver?";
        
        public ConnectVirtualMidi() {
            Out = OutputDevice.InstalledDevices[GetOutDeviceNumber()];
        }

        /// <summary>
        /// Is the Virtual Midi driver connected?
        /// </summary>
        [PexMethod]
        public bool Connected() {
            return Out != null;
        }

        /// <summary>
        /// Scans through the connected output devices and sets _outDevice to match the one containing the LoopBe (Virtual Midi Driver).
        /// </summary>
        private void SetOutDeviceNumber() {
            if (OutputDevice.InstalledDevices.Count == 0) {
                throw new System.ArgumentException(Error);
            }
            int i = 0;
            foreach (OutputDevice device in OutputDevice.InstalledDevices) {
                if (device.Name.Contains("LoopBe")) {
                    _outDevice = i;
                    break;
                }
                i++;
            }
        }

        /// <summary>
        /// Tries to get the outDevice int. Throws an exception that is handled by MainController if no Virtual Midi driver is connected.
        /// </summary>
        private int GetOutDeviceNumber() {
            SetOutDeviceNumber();
            if (_outDevice == null)
                throw new System.ArgumentException(Error);
            return (int)_outDevice;
        }
    }
}
